using System;
using System;
using System.IO.Ports;
using System.Threading;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Sensor.SerialPorts;
using Sensor.SerialPorts.Enums;
using Sensor.UI.Models;
using Sensor.UI.Utils;
using Sensor.UI.Protocols;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Threading.Channels;

namespace Sensor.UI.ViewModels;

/// <summary>
/// 串口通信ViewModel，负责串口数据的接收和处理
/// </summary>
public partial class SerialPortViewModel : ViewModelBase, IDisposable
{
    // 串口配置属性
    [ObservableProperty]
    private string _port = string.Empty;
    
    [ObservableProperty]
    private int _baudRate = 115200;
    
    [ObservableProperty]
    private ParityBit _parityBit = ParityBit.None;
    
    [ObservableProperty]
    private StopBit _stopBit = StopBit.One;
    
    [ObservableProperty]
    private int _dataBit = 8;

    // 状态属性
    [ObservableProperty]
    private bool _isOpen = false;

    // 串口数据处理
    private readonly SerialPortHandler _serialPortHandler = new();
    private readonly TextProtocolSplitter _splitter = new();
    private readonly DataProcessor _dataProcessor = new();
    
    // 高性能数据处理组件
    private readonly HighSpeedDataProcessor _highSpeedDataProcessor;
    private readonly DataFlowController _dataFlowController;
    private readonly AdvancedPerformanceMonitor _performanceMonitor;

    // 事件
    public event EventHandler<byte[]>? DataReceived;
    public event EventHandler<string>? MessageReceived;
    public event EventHandler<SensorInfo>? SensorDataReceived;
    public event EventHandler<Exception>? ExceptionOccurred;

    public SerialPortViewModel()
    {
        // 初始化高性能组件
        _highSpeedDataProcessor = new HighSpeedDataProcessor();
        _dataFlowController = new DataFlowController(capacity: 10000);
        _performanceMonitor = new AdvancedPerformanceMonitor();

        // 设置高性能数据处理事件处理
        _highSpeedDataProcessor.OnDataReady += async (data) =>
        {
            // 通过数据流控制器处理数据
            if (_dataFlowController.TryAdd(Encoding.UTF8.GetBytes(data)))
            {
                // 数据已成功添加到流控制器
                await _performanceMonitor.RecordDataProcessedAsync(data.Length);
            }
            else
            {
                // 数据丢失，记录统计
                await _performanceMonitor.RecordDataLossAsync(data.Length);
            }
        };

        // 设置数据流控制器处理回调
        _dataFlowController.SetProcessingCallback(async (data, token) =>
        {
            // 处理数据并触发事件
            await ProcessDataAsync(data, token);
        });

        // 启动性能监控
        _ = Task.Run(async () => await _performanceMonitor.StartMonitoringAsync());
    }

    /// <summary>
    /// 打开串口
    /// </summary>
    public async Task<bool> OpenAsync()
    {
        if (IsOpen)
        {
            return true;
        }

        try
        {
            // 初始化状态
            _splitter.Reset();

            // 启动高性能数据处理组件
            _dataFlowController.Start();

            // 注册事件处理器
            _serialPortHandler.OnData += OnData;
            _serialPortHandler.OnException += OnException;

            // 打开串口
            bool result = _serialPortHandler.Open(Port, BaudRate, ParityBit, StopBit, DataBit);
            IsOpen = result;
            
            if (result)
            {
                AddMessage($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}]# 串口已打开: {Port} @ {BaudRate}");
            }
            
            return result;
        }
        catch (Exception ex)
        {
            AddMessage($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}]# 打开串口失败: {ex.Message}");
            IsOpen = false;
            return false;
        }
    }

    /// <summary>
    /// 关闭串口
    /// </summary>
    public async Task CloseAsync()
    {
        if (!IsOpen)
        {
            return;
        }

        try
        {
            // 停止高性能数据处理组件
            _dataFlowController.Stop();

            // 注销事件处理器
            _serialPortHandler.OnData -= OnData;
            _serialPortHandler.OnException -= OnException;

            // 关闭串口
            await _serialPortHandler.CloseAsync();

            IsOpen = false;
            AddMessage($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}]# 串口已关闭");
        }
        catch (Exception ex)
        {
            AddMessage($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}]# 关闭串口失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 数据接收处理
    /// </summary>
    private async void OnData(byte[] data)
    {
        // 使用高性能处理器处理数据
        if (_highSpeedDataProcessor != null)
        {
            // 直接传递字节数据，由处理器内部进行转换
            _highSpeedDataProcessor.AddData(data);
        }

        // 保留传统处理逻辑作为备用
        if (_dataProcessor != null)
        {
            try
            {
                _dataProcessor.Add(data);
            }
            catch (Exception ex)
            {
                AddMessage($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}]# 数据处理错误: {ex.Message}");
            }
        }

        // 更新性能统计
        if (_performanceMonitor != null)
        {
            _performanceMonitor.RecordDataReceived(data.Length);
        }

        // 触发数据接收事件
        DataReceived?.Invoke(this, data);
    }

    /// <summary>
    /// 高速数据处理方法
    /// </summary>
    private async Task ProcessDataAsync(byte[] data, CancellationToken token)
    {
        try
        {
            // 将字节数据转换为字符串用于显示
            string dataString = Encoding.UTF8.GetString(data);
            
            // 触发消息接收事件
            MessageReceived?.Invoke(this, dataString);
            
            // 解析协议数据为SensorInfo
            var protocolDatas = _splitter.Process(data);
            foreach (var protocolData in protocolDatas)
            {
                AddMessage($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}]# 数据接: {protocolData}   ");
                
                // 解析协议数据为SensorInfo
                var sensorInfo = TestProtocolSensorConverter.Process(protocolData);
                if (sensorInfo != null)
                {
                    // 触发传感器数据接收事件
                    SensorDataReceived?.Invoke(this, sensorInfo);
                }
                else 
                {
                    AddMessage($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}]# 数据格式解析出错: {protocolData}");
                }
            }
            
            // 记录处理统计
            await _performanceMonitor.RecordDataProcessedAsync(data.Length, token);
        }
        catch (Exception ex)
        {
            AddMessage($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}]# 高速数据处理异常: {ex.Message}");
        }
    }

    /// <summary>
    /// 异常处理
    /// </summary>
    private void OnException(Exception ex)
    {
        AddMessage($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}]# 串口异常: {ex.Message}  ");
        ExceptionOccurred?.Invoke(this, ex);
    }

    /// <summary>
    /// 添加消息
    /// </summary>
    private void AddMessage(string message)
    {
        MessageReceived?.Invoke(this, message);
    }

    #region 资源释放
    private bool _disposedValue = false;

    /// <summary>
    /// 释放资源
    /// </summary>
    protected virtual void Dispose(bool disposing)
    {
        if (!_disposedValue)
        {
            if (disposing)
            {
                // 停止所有处理器
                _highSpeedDataProcessor?.Dispose();
                _dataFlowController?.Dispose();
                _performanceMonitor?.Dispose();

                // 停止传统处理器
                _dataProcessor?.Dispose();

                // 关闭串口
                _serialPortHandler?.Dispose();
            }

            _disposedValue = true;
        }
    }

    /// <summary>
    /// 析构函数
    /// </summary>
    ~SerialPortViewModel()
    {
        Dispose(false);
    }

    /// <summary>
    /// 实现IDisposable接口
    /// </summary>
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    #endregion
}